//
//  ViewController.swift
//  demo
//
//  Created by Xiaoping Tang on 2023/3/17.
//

import UIKit
import SwiftUI

public extension Notification.Name {
    static let vc2 = Notification.Name(rawValue: "vc2")
}

extension UIHostingController {
    convenience public init(rootView: Content, ignoreSafeArea: Bool) {
        self.init(rootView: rootView)
        
        if ignoreSafeArea {
            disableSafeArea()
        }
    }
    
    func disableSafeArea() {
        guard let viewClass = object_getClass(view) else { return }
        
        let viewSubclassName = String(cString: class_getName(viewClass)).appending("_IgnoreSafeArea")
        if let viewSubclass = NSClassFromString(viewSubclassName) {
            object_setClass(view, viewSubclass)
        }
        else {
            guard let viewClassNameUtf8 = (viewSubclassName as NSString).utf8String else { return }
            guard let viewSubclass = objc_allocateClassPair(viewClass, viewClassNameUtf8, 0) else { return }
            
            if let method = class_getInstanceMethod(UIView.self, #selector(getter: UIView.safeAreaInsets)) {
                let safeAreaInsets: @convention(block) (AnyObject) -> UIEdgeInsets = { _ in
                    return .zero
                }
                class_addMethod(viewSubclass, #selector(getter: UIView.safeAreaInsets), imp_implementationWithBlock(safeAreaInsets), method_getTypeEncoding(method))
            }
            
            objc_registerClassPair(viewSubclass)
            object_setClass(view, viewSubclass)
        }
    }
}

class ViewController: UIViewController {
    let vm = SwiftUIViewModel()
    var vc: UIHostingController<SwiftUIView>?
//    required init?(coder aDecoder: NSCoder) {
//
////        var v = SwiftUIView()
//        super.init(rootView: SwiftUIView(vm))
////        v.vc = self
//    }
//
//    override init(rootView: SwiftUIView) {
//        super.init(rootView: SwiftUIView(vm))
//    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.additionalSafeAreaInsets = UIEdgeInsets.zero
//        self.additionalSafeAreaInsets = UIEdgeInsets.zero
//        self.edgesForExtendedLayout = .all
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        self.view.backgroundColor = UIColor.red
        NotificationCenter.default.addObserver(self, selector: #selector(showVC2), name: .vc2, object: nil)
        // Do any additional setup after loading the view.
//        self.definesPresentationContext = true
//        self.modalPresentationStyle = .pageSheet
//        self.modalTransitionStyle = .coverVertical
//        self.providesPresentationContextTransitionStyle = true
        
        addSwiftUIView()
        
        let btn = UIButton(frame: CGRect(x: 60, y: 400, width: 40, height: 40))
        btn.setTitle("UIKit", for: .normal)
        btn.setTitle("UIKit", for: .highlighted)
        btn.setTitleColor(UIColor.black, for: .normal)
        btn.layer.borderColor = UIColor.gray.cgColor
        btn.layer.borderWidth = 1
        btn.addTarget(self, action: #selector(touchTest), for: .touchUpInside)
        self.view.addSubview(btn)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    func addSwiftUIView() {
        let rootView = SwiftUIView(vm)
        let vc = UIHostingController(rootView: rootView)
        view.addSubview(vc.view)
//        vc.view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100)
        vc.view.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            vc.view.topAnchor.constraint(equalTo: view.topAnchor),
            vc.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            vc.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            vc.view.heightAnchor.constraint(equalToConstant: 200)
//            vc.view.widthAnchor.constraint(equalToConstant: 100)
        ])
        addChild(vc)
        vc.didMove(toParent: self)
        self.vc = vc
    }
    
    @objc func showVC2() {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        
        let vc = storyboard.instantiateViewController(withIdentifier: "ViewController2")
//        vc.modalPresentationStyle = .fullScreen
        let nav = UINavigationController(rootViewController: vc)
        nav.definesPresentationContext = true
        nav.providesPresentationContextTransitionStyle = true
        self.present(nav, animated: true)
    }
    
    @objc func touchTest() {
        print("touchTest")
//        self.vc?.updateFocusIfNeeded()
//        self.vc?.setNeedsFocusUpdate()
//        self.vc?.view.setNeedsLayout()
//        self.vc?.view.layoutIfNeeded()
//        self.vc?.updateViewConstraints()
//        vm.updateId()
        self.vc?.view.bounds.origin.y = 0.01
        self.vc?.view.bounds.origin.y = .zero
//        self.vc?.endAppearanceTransition()
        
//        self.vc?.view.removeFromSuperview()
//        if let vc = self.vc {
//            self.view.addSubview(vc.view)
//            NSLayoutConstraint.activate([
//                vc.view.topAnchor.constraint(equalTo: view.topAnchor),
//                vc.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
//                vc.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
//                vc.view.heightAnchor.constraint(equalToConstant: 200)
//            ])
//        }
        
//        addSwiftUIView()
    }
}

